package com.ericscode.html5.example.websocket.server;

import java.io.*;
import java.net.*;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class JavaSocketServer {
	/*
	 * Constants
	 */
	private static final int BACKLOG = 10;

	/*
	 * Logging
	 */
	private static final Logger logger = LoggerFactory.getLogger(JavaSocketServer.class);
	
	/*
	 * Socket
	 */
	private static ServerSocket providerSocket;
	private static Socket connection = null;
	
	/*
	 * IO Streams 
	 */
	private static ObjectOutputStream out;
	private static ObjectInputStream in;
	
	private JavaSocketServer() {}
	
	public static void startWebsocketServer(int port) {
		String message = null;
		try {
			// creating a server socket
			providerSocket = new ServerSocket(port, BACKLOG);
			
			// wait for a connection
			logger.info("Waiting for a connection");
			connection = providerSocket.accept();
			logger.info("Connection established with " + connection.getInetAddress().getHostName());
			
			// get IO streams
			out = new ObjectOutputStream(connection.getOutputStream());
			out.flush();
			//in = new ObjectInputStream(connection.getInputStream());
			sendMessage("Connection successful");
			
			// message communication untill 'bye'
			do{
				try{
					message = (String)in.readObject();
					System.out.println("client>" + message);
					if (message.equals("bye"))
						sendMessage("bye");
				}
				catch(ClassNotFoundException classnot){
					System.err.println("Data received in unknown format");
				}
			}while(!message.equals("bye"));
			
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			// close connection
			try{
				in.close();
				out.close();
				providerSocket.close();
			}
			catch(IOException ioException){
				ioException.printStackTrace();
			}
		}
	}
	
	private static void sendMessage(String msg)
	{
		try{
			out.writeObject(msg);
			out.flush();
			System.out.println("server>" + msg);
		}
		catch(IOException ioException){
			ioException.printStackTrace();
		}
	}
}
